package com.tql.view.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.tql.view.pojo.Scenery;
import com.tql.view.pojo.User;
import com.tql.view.service.SceneryService;
import com.tql.view.service.UserService;
import com.tql.view.util.DateUtil;
import com.tql.view.util.JsonUtil;
import com.tql.view.util.RedisUtil;
import com.tql.view.util.XLSUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    private SceneryService sceneryService;
    @Autowired
    private XLSUtils xlsUtils;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @RequestMapping("/user/toUserMain")
    public String toUserMain(){
        return "user/userMain";
    }
    //跳转到用户修改页面
    @RequestMapping("/user/toUpdateInformation")
    public String toUpdateInformation(){
        return "/user/updateInformation";
    }
    //修改用户信息
    @RequestMapping("/updateInformation")
    public String updateInformation(@RequestPart("username") String username,
                                    @RequestParam("email") String email,
                                    @RequestParam("password") String password,
                                    @RequestPart("face") MultipartFile face, HttpSession session){
        User user =(User)session.getAttribute("visitor");
        //建立Map集合存入key,value 赋值到数据库中的占位符，进行查询表
        Map<String,Object> params=new HashMap<>();
        params.put("account",user.getAccount());
        params.put("password",password);
        params.put("email",email);
        params.put("username",username);
        if(face.isEmpty()){
            params.put("image",user.getImage());
        }
        //判断上传文件是否为空
        if(!face.isEmpty()){
            try {

                //获取文件名称
                String originalFilename=face.getOriginalFilename();
                //随机生成图片后缀，UUID生成随机数+ '.jpg' 保证图片名唯一
                String finalFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                face.transferTo(new File("E://view//image//"+finalFileName));
                String path="/image/"+finalFileName;
                params.put("image",path);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        userService.updateInfomation(params);
        User user2=userService.getUserByAccount(user.getAccount());
        session.setAttribute("visitor",user2);
        return "user/userMain";


    }
    /*
     * 个人收藏
     * */
    @RequestMapping("/user/collect")
    public String collect(@RequestParam(defaultValue = "1")Integer pageNum,
                          @RequestParam(defaultValue = "12") Integer size,
                          Model model,
                          HttpSession session){
        User user= (User) session.getAttribute("visitor");
        String account=user.getAccount();
        int num= (int) redisUtil.lGetListSize(account);
        int totnum;
        List<Object> list = null;
        //初始条数
        int firstIndex = (pageNum - 1) * size;
        //到第几条数据结束
        int lastIndex = pageNum * size;
        //判断总共多少页
        if(num%size==0){
            totnum=num/size;
        }else{
            totnum=num/size+1;
        }
        if(pageNum<=totnum){
            list=redisUtil.lGet(account,firstIndex,lastIndex-1);
        }
        if(pageNum>totnum){
            pageNum=totnum;
            list=redisUtil.lGet(account,(totnum - 1) * size,num);
        }
        //获取用户收藏信息

        model.addAttribute("evaluate",list);
        model.addAttribute("newpage",pageNum);
        model.addAttribute("totle",totnum);
        model.addAttribute("sumnum",num);
        return "user/collect";

    }
    /*
     * 用户添加图片收藏
     * */
    @RequestMapping("/toaddCollect")
    public String addCollect(@RequestParam("image")String image,HttpSession session) throws InterruptedException {

        User user= (User) session.getAttribute("visitor");
        String account=user.getAccount();
        //用户account为主键，list集合保存用户收藏的图片信息
        redisUtil.lpush(account,image);
        int num= (int) redisUtil.lGetListSize(account);
        Thread.sleep(3000);
        return "redirect:/user/collect";
    }
    /*
    * 用户注册
    * */
    @RequestMapping("/toRegist")
    public String toRegist(){
        return "/user/regist";
    }
    @RequestMapping("/regist")
    public String v(@RequestPart("username") String username,
                                    @RequestParam("account") String account,
                                    String email,
                                    @RequestParam("password") String password,
                                    @RequestPart("face") MultipartFile face, HttpSession session){
        User user= (User) session.getAttribute("visitor");
        Map<String,Object> params=new HashMap<>();
        params.put("account",account);
        params.put("password",password);
        params.put("email",email);
        //角色赋值
        params.put("role","user");
        if(user!=null&&user.getRole().equals("admin")){
            //角色赋值
            params.put("role","admin");
        }
        params.put("username",username);
        if(face.isEmpty()){
            params.put("image","/images/scenery/5.jpg");
        }
        //判断上传文件是否为空
        if(!face.isEmpty()){
            try {


                //获取文件名称
                String originalFilename=face.getOriginalFilename();
                //随机生成图片后缀，UUID生成随机数+ '.jpg' 保证图片名唯一
                String finalFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                face.transferTo(new File("E://view//image//"+finalFileName));
                String path="/image/"+finalFileName;
                params.put("image",path);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        userService.userRegist(params);

        return "redirect:/toView";
    }
    /*
    * 获取所有用户信息，分页展示
    *
    * */
    @RequestMapping("/user/selectAllUser")
    public String selectAllUser(Model model,
                                @RequestParam(defaultValue = "1")Integer pageNum,
                                @RequestParam(defaultValue = "12") Integer size){
        List<User> list=userService.selectAllUser(pageNum,size);
        PageInfo pageInfo=new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/getUser";
    }
    /*
    * 根据用户account删除用户
    *
    * */
    @RequestMapping("/user/deleteUser")
    public String deleteUser(@RequestParam("account")String account){
        userService.deleteUser(account);
        return "redirect:/user/selectAllUser";
    }
    //导出所有用户的信息，生成表格
    @RequestMapping("/exportUser")
    public void exportUser(HttpServletResponse response) {
        List<User> monthReportModels = userService.getAllUser();
        // Excel标题
        String[] title = {"用户名", "账号", "邮箱", "角色"};
        // Excel文件名
        String fileName = "用户信息表.xls";
        // sheet名
        String sheetName = "用户信息";
        // 将数据放到数组中
        String[][] content = new String[monthReportModels.size()][title.length];
        for (int i = 0; i < monthReportModels.size(); i++) {
            User monthReportModel = monthReportModels.get(i);
            content[i][0] = monthReportModel.getUsername();
            content[i][1] = monthReportModel.getAccount();
            content[i][2] = monthReportModel.getEmail();
            content[i][3] = monthReportModel.getRole();
        }
        // 导出Excel
        try {
            HSSFWorkbook hssfWorkbook = xlsUtils.getHSSFWorkbook(sheetName, title, content, null);
            xlsUtils.setResponseHeader(response, fileName);
            OutputStream outputStream = response.getOutputStream();
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //签到
    @RequestMapping("/user/reward")
    @ResponseBody
    public String reward(HttpSession session){
        User user= (User) session.getAttribute("visitor");

        userService.updateReward(user.getAccount());
        return "签到成功";
    }
    //签到
    @RequestMapping("/user/getreward")
    @ResponseBody
    public String getreward(HttpSession session){
        User user= (User) session.getAttribute("visitor");

        Integer num=userService.getReward(user.getAccount());
        return num.toString();
    }
    @RequestMapping("/updatebackground")
    public String updatebackground(String myurl,HttpSession session){
        User user= (User) session.getAttribute("visitor");
       userService.updateBackGround(myurl,user.getAccount());
        return "user/userMain";
    }
    @RequestMapping("/user/getbackground")
    @ResponseBody
    public String getbackground(HttpSession session){
        User user= (User) session.getAttribute("visitor");
        String str=userService.getBackCround1(user.getAccount());
        return JsonUtil.objectToJson(str);
    }
    //跳转上传图片页面
    @RequestMapping("/user/toaddScenery")
    public String toaddScenery(){
        return "user/addScenery";
    }
    /*
     * 上传图片资源
     * */
    @RequestMapping("/user/insertScenery")
    public String insertScenery(@RequestParam("mytype")String mytype,
                                @RequestPart("face") MultipartFile face,
                                @RequestParam("myname")String myname,
                                @RequestParam("describes")String describes,
                                HttpSession session) {
        //默认时间
        String mydate="2021-10-25 12:39:42";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(mydate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //生成唯一标识符
        String id = UUID.randomUUID().toString();
        String path="";
        int pageview=0;
        //判断上传文件是否为空
        if (!face.isEmpty()) {
            try {

                //获取文件名称
                String originalFilename = face.getOriginalFilename();
                //随机生成图片后缀，UUID生成随机数+ '.jpg' 保证图片名唯一
                String finalFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                face.transferTo(new File("E://view//"+mytype+"//" + finalFileName));
                path = "/"+mytype+"/" + finalFileName;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        Scenery scenery=new Scenery(id,myname,path,describes,date,mytype,pageview,0);
        User user= (User) session.getAttribute("visitor");
        userService.updateReward(user.getAccount());
        //存入redis 缓存中
        redisUtil.lpush("views",scenery,86400);
        return "redirect:/scenery/getSceneryByPageView";

    }
    //签到
    @RequestMapping("/user/reward1")
    @ResponseBody
    public String reward1(HttpSession session){
        User user= (User) session.getAttribute("visitor");
        userService.updateReward1(user.getAccount());
        return "hello";
    }
    //获取通知
    @RequestMapping("/getNotice1")
    @ResponseBody
    public String getNotice1(){
        String notice= (String) redisUtil.lGetIndex("notice",0);
        return JsonUtil.objectToJson(notice);
    }
    //会员支付
    @RequestMapping("/toUserMain1")
    public String toUserMain1(HttpSession session){
        User user= (User) session.getAttribute("visitor");
        userService.updateReward2(user.getAccount(),100);
        int num=userService.getReward(user.getAccount());
        return "user/userMain";
    }

}

